package com.kadron.users;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.Component;
import org.jboss.seam.transaction.Transaction;

import com.kadron.common.KConst;
import com.kadron.dao.KUserDAO;
import com.kadron.entity.User;
import com.kadron.exceptions.KVersionException;
import com.kadron.manager.KMessageManager;
import com.kadron.service.UserHistoryService;

public abstract class AbstractUserManager extends KMessageManager {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1474773871997451872L;
	
	private static final Log log = LogFactory.getLog(AbstractUserManager.class);
	
	public void blockUnblock(User user) {
		if (user == null) {
			bad(KConst.BAD_THING);
			return;
		}
		boolean blocked = user.isBlocked();
		user.setBlocked(!blocked);
		javax.transaction.UserTransaction transaction = null;
		boolean rollback = false;
		KUserDAO userDAO = (KUserDAO) Component.getInstance("userDAO");
		try {
			transaction = Transaction.instance();
			user = (User) userDAO.updateVersioned(user);
			transaction.commit();
		} catch (KVersionException e) {
			if (log.isDebugEnabled()) {
				log.debug("User was already updated");
			}
			bad(KConst.VERSION_CHANGED);
			rollback = true;
		} catch (Exception e) {
			e.printStackTrace();
			bad(KConst.BAD_THING);
			rollback = true;
		}
		try {
			if (rollback && transaction != null) {
				transaction.rollback();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		good();
	}
	
	public void alarm(User user) {
		if (user == null) {
			bad(KConst.BAD_THING);
			return;
		}
		user.setAlarm(!user.isAlarm());
		javax.transaction.UserTransaction transaction = null;
		boolean rollback = false;
		KUserDAO userDAO = (KUserDAO) Component.getInstance("userDAO");
		UserHistoryService userHistoryService = (UserHistoryService) Component.getInstance("userHistoryService");
		try {
			transaction = Transaction.instance();
			user = (User) userDAO.updateVersioned(user);
			userHistoryService.create(user, "ALARM", "ALARM", "User set to alarm="+user.isAlarm());
			transaction.commit();
		} catch (KVersionException e) {
			if (log.isDebugEnabled()) {
				log.debug("User was already updated");
			}
			bad(KConst.VERSION_CHANGED);
			rollback = true;
		} catch (Exception e) {
			e.printStackTrace();
			bad(KConst.BAD_THING);
			rollback = true;
		}
		try {
			if (rollback && transaction != null) {
				transaction.rollback();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		good();
	}
	
}
